/**
 * @Description:
 * @Author 卞鹏飞 <228443632@qq.com>
 * @create 27/08/24 AM9:36
 */

import { defineAPIMock, Result } from '@zsamc/app/mock/shared.mjs'
import path from 'node:path'
import { ROOT_PATH } from '@zsamc/app/mock/utils'
import fs from 'node:fs'
import shell from 'shelljs'
import { PRETTIER_CONFIG_PATH } from '@internal/scripts/utils'
import { EOL } from 'node:os'

export default defineAPIMock({
  /**
   * 更新本地字典ts文件
   * @return {{code: number, data: {}, message: string}}
   * @constructor
   */
  'POST /dict/updateLocalDictTsFile': (req, res) => {
    const tsFile = path.join(ROOT_PATH, 'types/system/dict-keys.ts')
    // console.log(req.body, res.data)

    const data = req.body || []
    const content =
      `const tempServerDictObj = {` +
      data
        .map((item) => {
          // return `
          //   /** ${item?.dictName || ''} */
          //   '${item?.dictCode || ''}'
          // `

          const dictChildrenLabel = (item?.children || [])
            .map((cItem) => `${cItem.dictItemCode}: ${cItem.dictItemName}`)
            .join('、')

          return `
            /** ${dictChildrenLabel || ''} */
            /** ${item?.dictName || ''} */
            '${item?.dictCode || ''}': '${item?.dictName || ''}',
          `
        })
        .join(EOL) +
      `
          }
          export type TDictKeys = keyof typeof tempServerDictObj;
        `
    fs.writeFileSync(tsFile, content, 'utf-8')
    if (shell.exec(`prettier ${tsFile} --config --ignore-unknown ${PRETTIER_CONFIG_PATH} --write`).code !== 0) {
      res.end(Result.err({ message: '更新失败' }))
    } else {
      res.end(Result({ code: 200, message: 'ok' }))
    }
  },
  /**
   * 更新本地字典ts文件
   * @return {{code: number, data: {}, message: string}}
   * @constructor
   */
  'POST /dict/updateLocalParamTsFile': (req, res) => {
    const tsFile = path.join(ROOT_PATH, 'types/system/param-keys.ts')
    // console.log(req.body, res.data)

    const data = req.body || []
    const content =
      `const tempServerParamObj = {` +
      data
        .map((item) => {
          // return `
          //   /** ${item?.dictName || ''} */
          //   '${item?.dictCode || ''}'
          // `
          return `
            /** ${item?.configDesc || ''} */
            '${item?.configKey || ''}': '${item?.configName || ''}',
          `
        })
        .join(EOL) +
      `
          }
          export type TParamKeys = keyof typeof tempServerParamObj;
        `
    fs.writeFileSync(tsFile, content, 'utf-8')
    if (shell.exec(`prettier ${tsFile} --config --ignore-unknown ${PRETTIER_CONFIG_PATH} --write`).code !== 0) {
      res.end(Result.err({ message: '更新失败' }))
    } else {
      res.end(Result({ code: 200, message: 'ok' }))
    }
  }
})
